package com.bj58.groupbuy.action.interceptors;

import javax.servlet.http.HttpServletRequest;

import com.bj58.groupbuy.action.model.User;
import com.bj58.groupbuy.action.service.UserManagerService;
import com.bj58.groupbuy.action.util.SomePublicUtil;
import com.bj58.groupbuy.service.locator.ServiceLocator;
import com.bj58.wf.log.Log;
import com.bj58.wf.log.LogFactory;
import com.bj58.wf.mvc.ActionResult;
import com.bj58.wf.mvc.BeatContext;
import com.bj58.wf.mvc.interceptor.ActionInterceptor;

/**用户菜单权限校验拦截器
 * @author huangliang
 *
 */
public class CheckInterceptor implements ActionInterceptor {
	private UserManagerService userManagerService = ServiceLocator.get(UserManagerService.class);
	private SomePublicUtil spu = new SomePublicUtil();
	
	private Log log = LogFactory.getLog(this.getClass());
	
	/* 校验逻辑:
	 * 1.check注解无参数则以URI为校验对象
	 * 2.check注解有参数
	 *     OR  1).自定义报表查询（报表）时 参数 = irsearch ，此时将URI中的search替换为create，再以URI为校验对象
	 *     OR  2).自定义报表查询（图表）时 参数 = chartirsearch ，此时将URI中的chartsearch替换为create，再以URI为校验对象
	 *     OR  3).就以check注解参数(前面加上"/")为校验对象
	 */
	public ActionResult preExecute(BeatContext beat) {
		try {
			HttpServletRequest request = beat.getRequest();
			String requestURL = request.getRequestURI();
			
			Check check = beat.getAction().getActionMethod().getAnnotation(Check.class);
			String setUrl  = check.value();
			
			String checkUrl = "";
			
			if("".equals(setUrl) || null == setUrl){
				checkUrl = requestURL;
			}else if("irsearch".equals(setUrl)){
				checkUrl = requestURL.replace("search", "create");
			}else if("chartirsearch".equals(setUrl)){
				checkUrl = requestURL.replace("chartsearch", "create");
			}else{
				checkUrl = "/" + setUrl;
			}
			
			User user = spu.getUserByCookie(request);
			if(null == user || "".equals(user.getUsername())){
				return ActionResult.view("default/login");
			}
			
			if(!userManagerService.checkUserMenuFuns(user, checkUrl)){
				log.info("No permission , user is " + user.getUsername()+" , checkUrl is " + checkUrl);
				return ActionResult.view("default/check");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

}
